//cookie相关操作
function delCookie(name) {
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval = getCookie(name);
  if (cval)
    document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
};

function getCookie(name) {
  var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  if (arr = document.cookie.match(reg)) {
    return unescape(arr[2]);
  } else {
    return null;
  }
};

function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  var expires = "expires=" + d.toUTCString();
  document.cookie = cname + "=" + cvalue + "; " + expires;
};
//获取地址参数
function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
};
//全局公共参数
var versions = 1.6, //181114新增版本号 具体变更参加readme
  isApp = getQueryString('isApp'),
  errorGatherUrl, userDataInfo = JSON.parse(unescape(getCookie('zmtH5Mall'))),
  zmtH5MallId = JSON.parse(unescape(getCookie('zmtH5MallId'))),
  zmtH5MallShareId = JSON.parse(unescape(getCookie('zmtH5MallShareId'))),
  userId = !userDataInfo ? '' : userDataInfo.uniqueCode,
  openId = !userDataInfo ? '' : userDataInfo.openId,
  access_token = !userDataInfo ? '' : userDataInfo.access_token,
  token = access_token,
  shareUserId = !!getQueryString('shareUserId') ? getQueryString('shareUserId') : !!zmtH5MallId ? zmtH5MallId : '',
  shareShopCode = !!getQueryString('shareShopCode') ? getQueryString('shareShopCode') : !!zmtH5MallShareId ? zmtH5MallShareId : '',
  groupId, //拼团ID
  GroupType, //拼团类型
  activityId, //拼团活动ID
  virtualgoodsID, //主商品ID
  fullPrice, //拼团立省多少钱
  goodsName, //拼团商品名称
  isPtSuccess, //还需拼团人数
  sellingPointsDesc, //产品描述
  imgUrl, //分享产品图片
  shareInfo = new Object(); //反向拼团新增分享信息汇总

function ajaxTemplate(url, sucFn, Data, additional) { //ajax模板  第四个参数为跟app交互 or 后台报错无需登录开关 可以写成{nologin: 1}
  if (getQueryString('isApp') == 1) {
    Data.m_ = getQueryString('m_');
    Data.v_ = getQueryString('v_');
    Data.pt_ = getQueryString('pt_');
    Data.uid_ = getQueryString('uid_');
    Data.access_token = getQueryString('access_token');
  } else {
    Data.m_ = 'h5';
    Data.v_ = '1.0';
    !Data.pt_ ? Data.pt_ = 'fxh5c' : '';
    Data.uid_ = userId;
    !!access_token ? Data.access_token = access_token : '';
  };
  $.ajax({
    url: url,
    type: 'post',
    dataType: 'jsonp',
    jsonp: 'callback',
    async: false,
    data: Data,
    success: function(data) {
      if (data.tag == 1 && !additional) {
        if (data.errMsg == 'token time out.' || data.errMsg == "请求参数[access_token]不能为空！") {
          jumpLogin();
        } else {
          sucFn(data);
        };
      } else {
        sucFn(data);
      };
    },
    error: function(e) {
      console.log(e);
      if (!!additional) {
        additional.nologin == 1 ? errorGather(url, JSON.stringify(e)) : '';
      } else {
        jumpLogin();
      };
    }
  });
};
// 086a807587e70c885161ee6af24f126e
/*判断登录设备*/
var browser = {
  versions: function() {
    var u = navigator.userAgent,
      app = navigator.appVersion;
    return { //移动终端浏览器版本信息
      trident: u.indexOf('Trident') > -1,
      //IE内核
      presto: u.indexOf('Presto') > -1,
      //opera内核
      webKit: u.indexOf('AppleWebKit') > -1,
      //苹果、谷歌内核
      gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,
      //火狐内核
      mobile: !!u.match(/AppleWebKit.*Mobile.*/),
      //是否为移动终端
      ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
      //ios终端
      android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
      //android终端或uc浏览器
      iPhone: u.indexOf('iPhone') > -1,
      //是否为iPhone或者QQHD浏览器
      iPad: u.indexOf('iPad') > -1,
      //是否iPad
      webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
    };
  }(),
  language: (navigator.browserLanguage || navigator.language).toLowerCase()
};
//下载app封装
function downAppFun() {
  if (browser.versions.ios == true) {
    location.href = 'mitaohui://';
    setTimeout(function() {
      location.href = 'https://itunes.apple.com/cn/app/id1417124131?mt=8&time=' + new Date().getTime();
    }, 250);
    setTimeout(function() {
      location.reload();
    }, 1000);
    setTimeout(function() {
      history.back();
    }, 2000);
  } else {
    location.href = 'http://a.app.qq.com/o/simple.jsp?pkgname=com.simeiol.zimeihui&time=' + new Date().getTime();
  };
};
//微信判断
function is_weixn() {
  var ua = navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    return true;
  } else {
    return false;
  };
};
//动态增加分享判断
function addShareScript(url) {
  var oScript = document.createElement('script');
  oScript.type = 'text/javascript';
  oScript.charset = "utf-8";
  oScript.async = false;
  oScript.src = url;
  document.body.appendChild(oScript);
};
!!is_weixn ? addShareScript('https://res.wx.qq.com/open/js/jweixin-1.2.0.js') : '';
!!is_weixn ? addShareScript('../js/share.js?rev=@@hash19011401') : '';
//页面初始化加载动画
$(window).load(function() {
  if ($(".loadImgBox")) {
    $("video").removeClass("hide").show();
    $(".loadImgBox").addClass("rgba").hide();
  }
});
//百度统计
$('head').append("<script>var _hmt = _hmt || [];(function() {var hm = document.createElement(\"script\");hm.src =\"https://hm.baidu.com/hm.js?d61d718c42a33fb796e4dd88b90995cc\";var s =document.getElementsByTagName(\"script\")[0];s.parentNode.insertBefore(hm, s);})();</script>");

function addCssByLink(url, switCh) { //动态设置icon
  var doc = document;
  var link = doc.createElement("link");
  switCh == 0 ? link.setAttribute("rel", "apple-touch-icon") : link.setAttribute("rel", "icon");
  link.setAttribute("href", url);

  var heads = doc.getElementsByTagName("head");
  if (heads.length)
    heads[0].appendChild(link);
  else
    doc.documentElement.appendChild(link);
};
if (!!getQueryString('isFx')) {
  addCssByLink('../img/logo100.png', 0);
  addCssByLink('../img/logo100.png', 1);
};
//打印封装
function log(data) {
  console.log(data);
};
//跳转商品详情封装方便管理
function jumpProductDetails(productId) {
  location.href = "../html/productDetails.html?isFx=1&productId=" + productId;
};
//跳转拼团商品详情封装方便管理
function jumpPtProductDetails(productId, activityId) {
  location.href = "../html/PtProductDetails.html?productId=" + productId + "&activityId=" + activityId;
};
//跳转登录页统一封装
function jumpLogin() {
  var logoutInfo = new Object();
  logoutInfo.openId = versions > 1.3 ? '' : openId;
  logoutInfo.uniqueCode = versions > 1.3 ? '' : userId;
  logoutInfo.access_token = '';
  setCookie('zmtH5Mall', escape(JSON.stringify(logoutInfo)), 30);
  var locationUrl = window.location.href.split('/html/')[1],
    locationInfo = locationUrl.indexOf('?') > 0 ? locationUrl.split('?')[1] : 'login=success',
    locationAddress = locationUrl.split('.html')[0];
  setCookie('zmtH5MallUrl', escape(JSON.stringify(locationInfo)), 30);
  location.href = "../html/login.html?zmhUrl=" + locationAddress + '.html';
};
//动态渲染头部标题 - 不知道具体页面dom放置位置 - 所以只进行js渲染数据 不渲染dom
//开发环境 模拟参数 shareUserId=U398242 - 获取用户分享信息名字段叫shareUserId
function getShareInfo() {
  setCookie('zmtH5MallId', escape(JSON.stringify(shareUserId)), 30);
  setCookie('zmtH5MallShareId', escape(JSON.stringify(shareShopCode)), 30);
  ajaxTemplate(addressUrl + SERVICE.queryShopCode, function(data) {
    if (data.tag == 0) {
      var headImg = data.data.result.headImageUrl.indexOf('/group1/M00/') > 0 ? data.data.result.headImageUrl + '_100x15000.jpg' : data.data.result.headImageUrl;
      $('#supernatant .getCommonHead').attr('src', headImg);
      $('#supernatant .getCommonName').html(data.data.result.nickName);
      $('#supernatant .getCommonCode u').html(data.data.result.shopCode);
      $("#on").off().on('click', function() {
        downAppFun();
      });
    } else {
      $('#supernatant').hide();
    };
  }, {
    userId: shareUserId
  });
};
!!shareUserId ? getShareInfo() : $('#supernatant').hide();
//错误收集 181027新增
//域名验证
if (addressTest == "https://testsvr.meetao.com/") {
  errorGatherUrl = 'https://testlogs.meetao.com';
} else if (addressTest == "https://presvr.meetao.com/") {
  errorGatherUrl = 'https://prelogs.meetao.com';
} else if (addressTest == "https://svr.meetao.com/") {
  errorGatherUrl = 'https://logs.meetao.com';
} else {
  errorGatherUrl = 'https://graylogs.meetao.com';
};
var errorSnum = 1,
  errorSurl = '';

function errorGather(urlData, data) { //需要验证下 请求的地址是不是上次的地址 去除重复请求
  errorSurl == urlData ? errorSnum = 2 : errorSnum = 1;
  errorSurl = urlData;
  ajaxTemplate(errorGatherUrl + SERVICE.errorInfo, function() {}, {
    errMsg: data,
    interfaceUrl: urlData
  }, {
    nologin: errorSnum
  });
};

function time(t) { //倒计时
  var date = new Date(t);
  Y = date.getFullYear() + '-';
  M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  D = date.getDate() + ' ';
  h = date.getHours() + ':';
  m = date.getMinutes() + ':';
  s = date.getSeconds();
  return (Y + M + D + h + m);
};

function str2asc(strstr) { //后台加密参数
  return ("0" + strstr.charCodeAt(0).toString(16)).slice(-2);
};

function UrlEncode(str) { //后台加密参数
  var ret = "";
  var strSpecial = "!\"#$%&()*+,/:;<=>?[]^`{|}~%";
  var tt = "";
  for (var i = 0; i < str.length; i++) {
    var chr = str.charAt(i);
    var c = str2asc(chr);
    tt += chr + ":" + c + "n";
    if (parseInt("0x" + c) > 0x7f) {
      ret += "%" + c.slice(0, 2) + "%" + c.slice(-2);
    } else {
      if (chr == " ")
        ret += "+";
      else if (strSpecial.indexOf(chr) != -1)
        ret += "%" + c.toString(16);
      else
        ret += chr;
    }
  }
  return ret;
};

function getByteLen(val, num) { //判断字符长度

  var len = 0;
  for (var i = 0; i < val.length; i++) {
    var a = val.charAt(i);
    if (a.match(/[^\x00-\xff]/ig) != null) {
      len += 2;
    } else {
      len += 1;
    }
  }
  return len;
};

// 反向拼团 分享回调请求汇总
// 保存票选优品活动分享日志接口（丁）
function saveShareLog(shareType) {
  if (!!shareInfo.pageType) {
    ajaxTemplate(addressTest + SERVICE.saveShareLog, function(data) {}, {
      userId: userId,
      voteActivityCode: shareInfo.voteActivityCode, //	票选优品活动code，能获取到则传入
      voteItemCode: shareInfo.voteItemCode, //	票选优品活动投票项code，能获取到则传入
      pageType: shareInfo.pageType,
      shareType: shareType
    }, {
      nologin: 1
    });
  };
};
